<?php

namespace app\shopping\controller;

use think\Controller;
/**
 * 购物车接口
 */
class Cart extends Controller
{
    public function __construct(){
        parent::__construct();
        $this->CartModel = model('Product.Cart');
        $this->BusinessModel = model('Business.User');
        $this->ProductModel = model('Product.Product');
        $this->AddressModel = model('Business.Address');
        $this->TypeModel = model('Product.Type');
        $this->OrderModel = model('Product.order.Order');
        $this->OrderProductModel = model('Product.order.Product');
        $this->RecordModel = model('Business.Record');
    }

    /**
     * 购物车列表
     *
     * @ApiTitle    (购物车列表)
     * @ApiSummary  (购物车列表)
     * @ApiMethod   (POST)
     * @ApiParams   (name="busid", type="int", required=true, description="客户ID")
     * @ApiParams   (name="ids", type="string", required=false, description="购物车id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功'
    * })
    */
    public function index(){
        if($this->request->isPost()){
            $busid = $this->request->param('busid',0,'trim');
            $ids = $this->request->param('ids',0,'trim');

            // 判断用户是否存在
            $business = $this->BusinessModel->find($busid);
            if(!$business){
                $this->error('用户不存在');
                exit;
            }

            $where = ['busid' => $busid];

            if(!empty($ids)){
                $where['cart.id'] = ['in',$ids];
            }

            $list = $this->CartModel
                ->with(['product'])
                ->where($where)
                ->select();

            if($list){
                $this->success('返回购物车列表成功',null,$list);
                exit;
            }else{
                $this->error('购物车内暂无数据');
                exit;
            }

        }
    }


    /**
     * 添加购物车
     *
     * @ApiTitle    (添加购物车)
     * @ApiSummary  (添加购物车)
     * @ApiMethod   (POST)
     * @ApiParams   (name="busid", type="int", required=true, description="客户ID")
     * @ApiParams   (name="proid", type="int", required=true, description="商品id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功'
    * })
    */
    public function add(){
        if($this->request->isPost()){
            $busid = $this->request->param('busid',0,'trim');
            $proid = $this->request->param('proid',0,'trim');

            $business = $this->BusinessModel->find($busid);
            // 先判断用户是否存在
            if(!$business){
                $this->error('用户不存在');
                exit;
            }

            // 先判断商品存不存在
            $product = $this->ProductModel->find($proid);

            if(!$product){
                $this->error('商品不存在');
                exit;
            }

            // 先去查找购物车中是否有这个商品
            $where = [
                'busid' => $busid,
                'proid' => $proid
            ];

            $cart = $this->CartModel->where($where)->find();

            if($cart){
                // 执行更新语句

                // 组装数据
                $nums = bcadd($cart['nums'],1);
                $price = $product['price'];
                $total = bcmul($price,$nums);
                $data = [
                    'id' => $cart['id'],
                    'nums' => $nums,
                    'price' => $price,
                    'total' => $total
                ];

                // 执行更新
                $result = $this->CartModel->validate('common/Product/Cart.edit')->isUpdate(true)->save($data);

                if($result === FALSE){
                    $this->error($this->CartModel->getError());
                }else{
                    $this->success('更新购物车数量成功');
                }
            }else{
                // 插入语句
                // 组装数据
                $data = [
                    'busid' => $busid,
                    'proid' => $proid,
                    'nums' => 1,
                    'price' => $product['price'],
                    'total' => $product['price']
                ];

                // 插入数据库
                $result = $this->CartModel->validate('common/Product/Cart')->save($data);

                if($result === FALSE){
                    $this->error($this->CartModel->getError());
                    exit;
                }else{
                    $this->success('添加购物车成功');
                    exit;
                }
            }
        }
    }

    /**
     * 修改购物车商品数量
     *
     * @ApiTitle    (修改购物车商品数量)
     * @ApiSummary  (修改购物车商品数量)
     * @ApiMethod   (POST)
     * @ApiParams   (name="busid", type="int", required=true, description="客户ID")
     * @ApiParams   (name="cartid", type="int", required=true, description="购物车id")
     * @ApiParams   (name="nums", type="int", required=true, description="数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功'
    * })
    */
    public function edit(){
        if($this->request->isPost()){
            $busid = $this->request->param('busid',0,'trim');
            $cartid = $this->request->param('cartid',0,'trim');
            $nums = $this->request->param('nums',0,'trim');

            // 先判断用户是否存在
            $business = $this->BusinessModel->find($busid);
            if(!$business){
                $this->error('用户不存在');
                exit;
            }

            // 判断购物车记录是否存在
            $cart = $this->CartModel->find($cartid);
            if(!$cart){
                $this->error('购物车记录不存在');
                exit;
            }

            // 判断商品是否存在
            $product = $this->ProductModel->find($cart['proid']);

            if(!$product){
                $this->error('商品不存在');
                exit;
            }
            
            if($nums <= 0){
                $this->error('购物车商品数量有误');
                exit;
            }

            // 更新购物车
            $price = $product['price'];
            $total = bcmul($price,$nums);
            
            // 组装数据
            $data = [
                'id' => $cartid,
                'nums' => $nums,
                'price' => $price,
                'total' => $total,
            ];

            // 执行更新语句
            $result = $this->CartModel->validate('common/Product/Cart.edit')->isUpdate(true)->save($data);

            if($result === FALSE){
                $this->error($this->CartModel->getError());
                exit;
            }else{
                $this->success('更新购物车商品数量成功');
                exit;
            }
        }
    }


    /**
     * 删除购物车中的商品
     *
     * @ApiTitle    (删除购物车中的商品)
     * @ApiSummary  (删除购物车中的商品)
     * @ApiMethod   (POST)
     * @ApiParams   (name="busid", type="int", required=true, description="客户ID")
     * @ApiParams   (name="cartid", type="int", required=true, description="购物车id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功'
    * })
    */
    public function del(){
        if($this->request->isPost()){
            $busid = $this->request->param('busid',0,'trim');
            $cartid = $this->request->param('cartid',0,'trim');

            // 判断用户是否存在
            $business = $this->BusinessModel->find($busid);
            if(!$business){
                $this->error('用户不存在');
                exit;
            }

            // 判断购物车记录是否存在
            $cart = $this->CartModel->find($cartid);
            if(!$cart){
                $this->error('购物车记录不存在');
                exit;
            }

            // 执行删除
            $result = $this->CartModel->where(['id'=>$cartid])->delete();

            if($result === FALSE){
                $this->error($this->CartModel->getError());
                exit;
            }else{
                $this->success('删除记录成功');
                exit;
            }
        }
    }


    /**
     * 获取收货地址
     *
     * @ApiTitle    (获取收货地址)
     * @ApiSummary  (获取收货地址)
     * @ApiMethod   (POST)
     * @ApiParams   (name="busid", type="int", required=true, description="客户ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功'
    * })
    */
    public function address(){
        if($this->request->isPost()){
            $busid = $this->request->param('busid',0,'trim');
            
            // 判断用户是否存在
            $business = $this->BusinessModel->find($busid);
            if(!$business){
                $this->error('用户不存在');
                exit;
            }

            // 查询收获地址
            $address = $this->AddressModel->where(['busid'=>$busid,'status'=>'1'])->find();
            if(!$address){
                $address = $this->AddressModel->where(['busid'=>$busid])->find();
            }

            if($address){
                $this->success('返回收货地址',null,$address);
                exit;
            }else{
                $this->error('暂无收获地址');
                exit;
            }
        }
    }

    /**
     * 立即购买
     *
     * @ApiTitle    (立即购买)
     * @ApiSummary  (立即购买)
     * @ApiMethod   (POST)
     * @ApiParams   (name="busid", type="int", required=true, description="客户ID")
     * @ApiParams   (name="proid", type="int", required=true, description="商品id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功'
    * })
    */
    public function buynow(){
        if($this->request->isPost()){
            // var_dump($this->request->param());
            // exit;
            $busid = $this->request->param('busid',0,'trim');
            $proid = $this->request->param('proid',0,'trim');
            $addrid = $this->request->param('addrid',0,'trim');
            $nums = $this->request->param('nums',1,'trim');
            $remark = $this->request->param('remark','','trim');

            // 查询用户
            $business = $this->BusinessModel->find($busid);
            if(!$business){
                $this->error('用户未知');
                exit;
            }

            // 查询商品
            $product = $this->ProductModel->with(['unit'])->find($proid);
            if(!$product){
                $this->error('商品信息未知');
                exit;
            }
            // 判断商品库存是否充足
            $UpdateStock = bcsub($product['stock'],$nums);
            if($UpdateStock < 0){
                $this->error('商品库存不足');
                exit;
            }

            // 判断客户余额是否充足
            $total = bcmul($product['price'],$nums);
            $UpdateMoney = bcsub($business['money'],$total);
            if($UpdateMoney < 0){
                $this->error('余额不足');
                exit;
            }

            // 查询地址
            $address = $this->AddressModel->find($addrid);
            if(!$address){
                $this->error('地址未知');
                exit;
            }

            // 订单表、订单商品表、商品表、消费记录表、用户表

            // 开启事务
            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->RecordModel->startTrans();
            $this->BusinessModel->startTrans();
            

            $OrderData = [
                'code' => build_code('SH'),
                'busid' => $busid,
                'businessaddrid' => $addrid,
                'amount' => $total,
                'remark' => $remark,
                'status' => 1
            ];

            $OrderStatus = $this->OrderModel->validate('common/Product/order/Order')->save($OrderData);
            if($OrderStatus === FALSE){
                $this->error($this->OrderModel->getError());
                exit;
            }

            $OrderProductData = [
                'orderid' => $this->OrderModel->id,
                'proid' => $proid,
                'pronum' => $nums,
                'price' => $product['price'],
                'total' => $total
            ];
            
            $OrderProductStatus = $this->OrderProductModel->validate('common/Product/order/Product')->save($OrderProductData);
            if($OrderProductStatus === FALSE){
                $this->OrderModel->rollback();
                $this->error($this->OrderProductModel->getError());
                exit;
            }

            $ProductData = [
                'id' => $proid,
                'stock' => $UpdateStock
            ];

            $ProductStatus = $this->ProductModel->isUpdate(true)->save($ProductData);
            if($ProductStatus === FALSE){
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->ProductModel->getError());
                exit;
            }

            $RecordData = [
                'total' => $total,
                'busid' => $busid,
                'content' => "购买了 {$nums} {$product['unit']['name']} {$product['name']} 花费了￥ {$total} 元"
            ];

            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
            if($RecordStatus === FALSE){
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }


            $BusinessData = [
                'id' => $busid,
                'money' => $UpdateMoney,
                'deal' => 1
            ];

            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);
            if($BusinessStatus === FALSE){
                $this->RecordModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            if($BusinessStatus === FALSE || $RecordStatus === FALSE || $ProductStatus === FALSE || $OrderProductStatus === FALSE || $OrderStatus === FALSE){
                $this->BusinessModel->rollback();
                $this->RecordModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error('购买失败');
                exit;
            }else{
                $this->BusinessModel->commit();
                $this->RecordModel->commit();
                $this->ProductModel->commit();
                $this->OrderProductModel->commit();
                $this->OrderModel->commit();
                $this->success('购买成功','/order/index');
                exit;
            }

        }
    }

    /**
     * 立即购买的商品信息
     *
     * @ApiTitle    (立即购买的商品信息)
     * @ApiSummary  (立即购买的商品信息)
     * @ApiMethod   (POST)
     * @ApiParams   (name="proid", type="int", required=true, description="商品id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功'
    * })
    */
    public function product(){
        if($this->request->isPost()){
            $proid = $this->request->param('proid',0,'trim');
            
            $product = $this->ProductModel->find($proid);
            if($product){
                $this->success('返回商品信息',null,$product);
                exit;
            }else{
                $this->error('商品信息未知');
                exit;
            }

        }
    }

}
